package com.road.vast.springboot.util;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.joda.time.DateTime;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author 郭泽鹏
 * @Date 2020/8/5 16:05
 * @Version 1.0
 * @Description 将Excel表中数据的格式转为String类型
 */
@Component
public class POIUtils {
    public String cellValueToStringUtils(Cell cell){
        //获取单元格数据类型
        CellType cellType = cell.getCellTypeEnum();
        String cellValue = "";
        switch (cellType){
            case STRING:        //字符串
                System.out.print("[STRING]");
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN:       //布尔类型
                System.out.print("[BOOLEAN]");
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case BLANK:
                System.out.print("[BLANK]");
                break;
            case NUMERIC:       //数字（可以分为日期和普通数字）
                System.out.print("[NUMERIC]");
                if (HSSFDateUtil.isCellDateFormatted(cell)){        //日期
                    System.out.println("[日期]");
                    Date date = cell.getDateCellValue();
                    cellValue = new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
                }else{
                    //防止数字过长，转换为字符串输出
                    System.out.print("[转换为字符串输出]");
                    cell.setCellType(CellType.STRING);
                    cellValue = cell.toString();
                }
                break;
            case ERROR:
                System.out.print("[数据类型错误]");
                break;
        }
        return cellValue;
    }
}
